#ifndef MYSQL_UTIL_HPP
#define MYSQL_UTIL_HPP

#include <mysql/mysql.h>
#include <string>
#include <openssl/evp.h>
#include <stdexcept>
#include "log.hpp"


using namespace ns_log;


class MySQLUtil {
private:
    MYSQL* conn;
public:
    MySQLUtil(const std::string& host,const std::string& user,const std::string& passwd,const std::string& db,unsigned int port = 3306);

    ~MySQLUtil();
        bool GetUserPassword(const std::string& username, std::string* password) {
        // 假设用户表名为user，字段为username和password（存储SHA256加密后的密码）
        std::string sql = "SELECT password FROM user WHERE username = ?";
        MYSQL_STMT* stmt = mysql_stmt_init(conn);
        if (!stmt) {
            LOG(ERROR) << "mysql_stmt_init failed";
            return false;
        }
        if (mysql_stmt_prepare(stmt, sql.c_str(), sql.size()) != 0) {
            LOG(ERROR) << "mysql_stmt_prepare failed: " << mysql_stmt_error(stmt);
            mysql_stmt_close(stmt);
            return false;
        }
        // 绑定参数（用户名）
        MYSQL_BIND param;
        memset(&param, 0, sizeof(param));
        param.buffer_type = MYSQL_TYPE_STRING;
        param.buffer = (char*)username.c_str();
        param.buffer_length = username.size();
        if (mysql_stmt_bind_param(stmt, &param) != 0) {
            LOG(ERROR) << "mysql_stmt_bind_param failed: " << mysql_stmt_error(stmt);
            mysql_stmt_close(stmt);
            return false;
        }
        // 执行查询
        if (mysql_stmt_execute(stmt) != 0) {
            LOG(ERROR) << "mysql_stmt_execute failed: " << mysql_stmt_error(stmt);
            mysql_stmt_close(stmt);
            return false;
        }
        // 绑定结果（密码）
        MYSQL_BIND result;
        memset(&result, 0, sizeof(result));
        char buf[65];  // SHA256加密后为64位字符串
        unsigned long len;
        result.buffer_type = MYSQL_TYPE_STRING;
        result.buffer = buf;
        result.buffer_length = 65;
        result.length = &len;
        if (mysql_stmt_bind_result(stmt, &result) != 0) {
            LOG(ERROR) << "mysql_stmt_bind_result failed: " << mysql_stmt_error(stmt);
            mysql_stmt_close(stmt);
            return false;
        }
        // 获取结果
        if (mysql_stmt_fetch(stmt) != 0) {
            // 用户名不存在
            mysql_stmt_close(stmt);
            return false;
        }
        *password = std::string(buf, len);
        mysql_stmt_close(stmt);
        return true;
    }

    // 注册用户
    bool RegisterUser(const std::string& username, const std::string& password);

  

    // 生成随机盐值
    static std::string GenerateSalt();

    // SHA256加密
static std::string SHA256(const std::string& str); // 关键声明
};

#endif